import axios from 'axios'
import { getToken } from '@/utils/auth'
import { blobValidate } from '@/utils/ruoyi'
import { Loading, Message } from 'element-ui'

let downloadLoadingInstance;

/**
 * 通过路径下载文件
 * @param path 路径
 * @param fileName 文件名
 */
export function downloadFileByPath(path, fileName) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  const token = getToken()
  axios({
    method: 'get',
    url: path,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + token }
  }).then(async (res) => {
    const isLogin = await blobValidate(res.data);
    if (isLogin) {
      const blob = new Blob([res.data])
      saveAs(blob, fileName)
    } else {
      Message.error('下载文件失败')
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}

/**
 * 保存文件
 * @param blob
 * @param fileName
 */
function saveAs(blob, fileName) {
  // ie兼容
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    const link = document.createElement('a');
    const body = document.querySelector('body');

    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;

    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}
